package com.winai.launcher;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;

import com.clj.fastble.BleManager;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.dueeeke.videoplayer.player.AndroidMediaPlayerFactory;
import com.dueeeke.videoplayer.player.VideoViewConfig;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.ks.projectbasictools.okhttp.OkHttpUtils;
import com.ks.projectbasictools.retrofit.ServerHttp;
import com.sdwfqin.cbt.CbtManager;
import com.squareup.picasso.Picasso;
import com.tencent.bugly.crashreport.CrashReport;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.constant.ScreenProtectConstant;
import com.winai.launcher.manager.AiyishengManager;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.ScreenProtectManager;
import com.winai.launcher.manager.VolumeWindow;
import com.winai.launcher.override.ActivityLifecycleListener;
import com.winai.launcher.override.HttpCacheResponse;
import com.winai.launcher.override.StringCallBackYu;
import com.winai.launcher.service.LocationService;
import com.winai.launcher.utils.AppCollectUtil;

import org.litepal.LitePal;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.utils.UuidUtils;

public class Application extends android.app.Application {
    private final String TAG = "Launcher Application";
    public static Context instance;
    public static WifiItemBean connectingWifi = null;//系统正在连接的WiFi
    private String SPP_UUID = "00001105-0000-1000-8000-00805f9B34FB";
    public static LocationService locationService;
    public static Activity homeActivity;

    @SuppressWarnings("unchecked")
    @Override
    public void onCreate() {
        super.onCreate();
        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        instance = getApplicationContext();
        //注册全局Activity生命周期回调
        registerActivityLifecycleCallbacks(new ActivityLifecycleListener());
        //带网络缓存的网络请求初始化
        ServerHttp.init(this.getApplicationContext(), this.getApplicationContext().getString(R.string.http_url), new HttpCacheResponse());
        ServerHttp.setUseCache(true);
        ServerHttp.setDebug(true);

        OkHttpUtils.init(this.getApplicationContext(), getString(R.string.http_url), new StringCallBackYu<>());
        OkHttpUtils.setDebug(true);
        //初始化数据库
        LitePal.initialize(Application.this);
        //Bugly，建议在测试阶段建议设置成true，发布时设置为false
        CrashReport.initCrashReport(getApplicationContext(), "147642c61f", false);
        //播放器
        VideoViewManager.setConfig(VideoViewConfig.newBuilder()
                .setLogEnabled(true)
                /*//使用使用IjkPlayer解码
                .setPlayerFactory(IjkPlayerFactory.create())
                //使用ExoPlayer解码
                .setPlayerFactory(ExoMediaPlayerFactory.create())*/
                //使用MediaPlayer解码
                .setPlayerFactory(AndroidMediaPlayerFactory.create())
                .build());
        getCacheData();
        //用户行为统计工具初始化
        AppCollectUtil.getInstance().init(Application.this);
        //音量按键
//        LRVolumeAdjustManager.registerApplication(this);
        //初始化音量弹窗  https://github.com/yhaolpz/FloatWindow
        VolumeWindow.getInstance(getApplicationContext());
        //Ble蓝牙工具库
        initBluetoothUtils();
        //经典蓝牙
        CbtManager.getInstance()
                .init(this)// 初始化
                .setUUID(SPP_UUID)//自定义UUID
                .enableLog(true);// 是否打印相关日志
//        initTypeface();//全局定义字体
        /*初始化QQ音乐*/
//        MusicPlugin.init(getApplicationContext(), MusicPlugin.TYPE_QQCAR);
        /*初始化AIDL*/
        AiyishengManager.getInstance(getApplicationContext());
        /*初始化网络监听*/
        NetworkManager.getInstance(getApplicationContext()).init();
        //初始化图片
        Picasso.setSingletonInstance(
                new Picasso.Builder(this)
                        // additional settings
                        .build());
        //初始化蓝牙
        initBle();
        WifiUtils.enableLog(true);
    }

    //初始化蓝牙
    private void initBle() {
        Ble.options().setLogBleEnable(true)//设置是否输出打印蓝牙日志
                .setThrowBleException(true)//设置是否抛出蓝牙异常
                .setLogTAG("AndroidBLE")//设置全局蓝牙操作日志TAG
                .setAutoConnect(false)//设置是否自动连接
                .setFilterScan(true)//设置是否过滤扫描到的设备
                .setConnectFailedRetryCount(10)
                .setConnectTimeout(30 * 1000)//设置连接超时时长
                .setScanPeriod(60 * 1000)//设置扫描时长
                .setUuidService(UUID.fromString(UuidUtils.uuid16To128("fee9", false)))//设置主服务的uuid
                .setUuidWriteCha(UUID.fromString("d44bc439-abfd-45a2-b575-925416129600"))//设置可写特征的uuid
                .create(instance);
    }

    /**
     * 说明：定义全局字体
     */
    private void initTypeface() {
        Typeface typefaceHeiTi = Typeface.createFromAsset(getAssets(), "HanSansCN.otf");
        try {
            Field field = Typeface.class.getDeclaredField("MONOSPACE");
            field.setAccessible(true);
            field.set(null, typefaceHeiTi);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void initBluetoothUtils() {
        //初始化
        BleManager.getInstance().init(this);
        //全局配置
        BleManager.getInstance()
                .enableLog(true)//显示框架内部日志
                .setReConnectCount(1, 5000)//重连次数和重连时间间隔
                .setSplitWriteNum(20)//设置分包发送的时候，每一包的数据长度，默认20个字节
                .setConnectOverTime(30000)//连接超时时间
                .setOperateTimeout(5000);//操作超时时间
        //配置扫描规则
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, names)         // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
                .setAutoConnect(true)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    /**
     * 说明：获取本地数据库的缓存数据
     */
    private void getCacheData() {
        /**
         * 获取屏保时长以及图片
         */
        DB_Common db_common = new DB_Common(this);
        String screenProtectTime = db_common.get(ScreenProtectConstant.TIME);
        String model = db_common.get(ScreenProtectConstant.MODEL);
        if (screenProtectTime != null) {
            ScreenProtectConstant.time = Integer.parseInt(screenProtectTime);
        }
        if (model != null) {
            switch (model) {
                case "static":
                    ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.STATIC);
                    ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.STATIC);
                    break;
                case "dynamic":
                    ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.DYNAMIC);
                    ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.DYNAMIC);
                    break;
                case "null":
                    ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.NULL);
                    ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.NULL);
                    break;
            }
        }
    }

    public static Activity getHomeActivity() {
        return homeActivity;
    }

    public static void setHomeActivity(Activity homeAct) {
        homeActivity = homeAct;
    }

    // 实例对象
    public static WeakReference<Activity> instanceRef;

    public static synchronized Context getInstance() {
        if (instanceRef == null || instanceRef.get() == null) {
            return Application.getContext();
        } else {
            return instanceRef.get();
        }
    }

    public static synchronized Context getContext() {
        return instance;
    }
}
